package com.mazaiting.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.common.core.utils.StringUtil;
import com.mazaiting.redis.service.IRedisService;
import com.mazaiting.sms.config.SmsProperties;
import com.mazaiting.sms.domain.dto.SmsDto;
import com.mazaiting.sms.service.ISmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/***
 * 短信服务实现
 * @author mazaiting
 * @create_time 2022/4/12 16:14
 */
@Slf4j
@Service
@Qualifier("aliSmsServiceImpl")
@RequiredArgsConstructor
public class AliSmsServiceImpl implements ISmsService {

    private final SmsProperties smsProperties;

    private final IRedisService redisService;

    @Override
    public boolean send(SmsDto smsDto) {
        SmsProperties.AliSmsProperties aliSmsProperties = smsProperties.getAli();
        // 手机号
        String phone = smsDto.getPhone();
        // 设置默认数据
        DefaultProfile profile = DefaultProfile.getProfile(aliSmsProperties.getRegionId(), aliSmsProperties.getKeyId(), aliSmsProperties.getKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(phone);
        String code = StringUtil.getRandomString(smsProperties.getDigits());
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            log.info("短信请求参数: " + JSON.toJSONString(request));
            SendSmsResponse response = client.getAcsResponse(request);
            if ("OK".equals(response.getCode())) {
                // 存入 redis
                redisService.set(SecurityConst.SMS_CODE_PREFIX + phone, code, smsProperties.getExpiration(), TimeUnit.SECONDS);
                log.info("短信发送成功: 手机号 - " + phone + ", 验证码: " + code);
                return true;
            } else {
                log.info("短信发送失败: 手机号 - " + phone + ", 验证码: " + code + ", 失败原因: " + response.getMessage());
            }
        } catch (ClientException e) {
            log.error("阿里云短信发送 sdk 调用失败: 请求 ID - " + e.getRequestId() + ", 异常码: " + e.getErrCode() + ", 异常信息: " + e.getErrMsg());
        } catch (Exception e) {
            log.error("阿里云短信发送失败: " + e.getMessage());
        }
        return false;
    }
}


















